var express = require('express');
var router = express.Router();
var config = require('../config/db')
var MongoClient = require('mongodb').MongoClient
var bcrypt = require('bcryptjs')
var passport=require('passport')
var mongdb = require('mongodb')

/* 查询轮播图 */
router.get('/getLoopsInfo', async function (req, res, next) {
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    let loops = await db.collection('loops').find({}).toArray()    //获取所有商品数据
    console.log('loops:', loops)
    if (loops.length > 0) {
        res.json({ code: 200, message: 'ok', data: loops });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});


/*添加轮播图 */
router.post('/addLoops', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    //获取需要添加的订单商品信息
    let loops = req.body.loop
    console.log('book: ', loops);
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    // //执行添加订单的操作
    let results = await db.collection('loops').insertOne(loops)
    //判断是否添加成功
    if (results.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});


// /* 删除轮播图 */
router.delete('/delLoops', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    // 获取需要删除的id
    let id = req.query.id
    console.log('id =', id)
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //执行删除的操作
    let results = await db.collection('loops').deleteOne({ _id: new mongdb.ObjectId(id) })
    console.log('results:', results)
    //判断是否删除成功
    if (results.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({
            code: 200, message: 'error'
        });
    }
});


/* 修改轮播图   */
router.get('/updLoops', function (req, res, next) {
    //1.接受修改轮播图需要使用的参数req.body（ loopId loopUrl 修改轮播图的图片url即可）
    var updLoops = req.body
    //2.连接数据库MongoDB
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            //3.执行修改轮播图操作  updateOne
            var db = client.db()
            db.collection('loop').updateOne({ loop_id: updLoops.loopId }, { $set: { loop_pic: updLoops.loopUrl } }, function (err, result) {
                if (err) {
                    console.log('修改数据失败！', err)
                } else {
                    //4.返回结果{code:0;message:'ok',data:{}}
                    res.json({ code: 200, message: 'ok', data: result })
                    client.close()
                }
            })
        }
    })
});

module.exports = router;